<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    @ok="handleOK"
   :title="t('sys.script.details')"
  >
    <Description :column="3" :data="mockData" :schema="schema" />
    <div class="tabelview">
      <BasicTable @register="registerTableModel" />
    </div>
    <PhaseView @register="registerphaseView" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { useModal, BasicModal, useModalInner } from '@/components/Modal';
  import { Description, DescItem } from '@/components/Description';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { ref, h, onUnmounted, computed, onMounted, nextTick } from 'vue';
  import { getDetailAPI, getMatchMaxAPI, taskStatusNumApi } from '@/api/demo/InformationMatching';
  import { detailPageAPI } from '@/api/demo/AdvertisingMarketing';
  import { columnsModels } from './account.data';
  import PhaseView from './phaseView.vue';
  import { Button, Input } from 'ant-design-vue';
  import { useECharts } from '@/hooks/web/useECharts';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const emit = defineEmits(['success']);
  const Data = ref<any>({});
  const mockData = ref({});
  const buttonLabels = ref([]);
  const modalWidth = ref('70%');
  let intervalId: number | null = null;
  let matchMaxIntervalId: number | null = null;

  const total = ref(0);
  const taskStatusData = ref<any[]>([]);
  const matching = ref('0.2'); // 初始化 matching 值
  const [registerphaseView, { openModal: openphaseView }] = useModal();
  const schema: DescItem[] = [
    { field: 'id', label: 'id', labelMinWidth: 150 },
    { field: 'createTime', label: t('sys.informaionMatchaing.columns.createTime'), labelMinWidth: 150 },
    { field: 'title', label: t('sys.informaionMatchaing.columns.title'), labelMinWidth: 150 },
    { field: 'content', label: t('sys.configuration.describe'), labelMinWidth: 150 },
    { field: 'district', label:  t('sys.informaionMatchaing.columns.district'), labelMinWidth: 150 },
    // { field: 'age', label:  t('sys.informaionMatchaing.columns.age'), labelMinWidth: 150 },
    // { field: 'gender', label:  t('sys.informaionMatchaing.columns.gender'), labelMinWidth: 150 },
    { field: 'audience', label:  t('sys.informaionMatchaing.columns.audience'), labelMinWidth: 150 },
    { field: 'interest', label:  t('sys.informaionMatchaing.columns.interest'), labelMinWidth: 150 },
    {
      field: 'status',
      label: t('sys.informaionMatchaing.columns.status'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        if (data.status === 0) {
          return t('sys.configuration.notStart');
        } else if (data.status === 1) {
          return '执行中';
        } else {
          return '执行成功';
        }
        return data.status;
      },
    },
    {
      field: 'success',
      label: t('sys.informaionMatchaing.columns.success'),
      labelMinWidth: 150,
      render: (val: any, data: Recordable) => {
        const success = data.success ?? '-';
        const total = data.total ?? '-';
        return `${success}/${total}`;
      },
    },
  ];

  const searchFormSchemaDtail = ref([
    {
      field: 'matching',
      label: t('sys.informaionMatchaing.columns.matching'),
      component: 'Input',
      colProps: { span: 4 },
      defaultValue: 0.2, // 使用 ref 确保 defaultValue 是响应式的
    },
  ]);

  const [registerTableModel, { reload, getForm }] = useTable({
    api: async ({ page, pageSize }) => {
      const result = await detailPageAPI({
        ...Data.value,
        page,
        pageSize,
      });
      return result;
    },
    rowKey: 'dataId',
    columns: columnsModels,
    showTableSetting: true,
    bordered: true,
    formConfig: {
      schemas: searchFormSchemaDtail,
      autoSubmitOnEnter: true,
      labelAlign: 'left',
    },
    useSearchForm: false,
    showIndexColumn: false,
  });
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions, getInstance } = useECharts(chartRef as Ref<HTMLDivElement>);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    Data.value = data.record;
    mockData.value = data.record;
    getMatchMax();
    setModalProps({ confirmLoading: false, showOkBtn: false });
    await reload();

    // 清除之前的定时器
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }

    // 启动新的定时器
    // intervalId = setInterval(async () => {
    //   await reload();
    // }, 5000);

    // 清除之前的 matchMax 定时器
    if (matchMaxIntervalId) {
      clearInterval(matchMaxIntervalId);
      matchMaxIntervalId = null;
    }
    // 启动新的 matchMax 定时器
    // matchMaxIntervalId = setInterval(async () => {
    //   await getMatchMax();
    // }, 5000);
  });

  function addse() {}
  async function getMatchMax() {
    let valueData = await getMatchMaxAPI(Data.value.id);
    buttonLabels.value = valueData.data.map((item) => ({
      label: Number(item.label).toFixed(2),
      value: item.value,
    }));

    // 获取 dataX 和 dataY
    const dataX = buttonLabels.value.map((item) => item.label);
    const dataY = buttonLabels.value.map((item) => item.value);

    setOptions({
      grid: {
        top: 20, // 设置顶部距离
        bottom: 20, // 设置底部距离
        left: 50, // 设置底部距离
        right: 20, // 设置底部距离
      },
      xAxis: {
        type: 'category',
        data: dataX,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: dataY,
          type: 'bar',
        },
      ],
      tooltip: {
        trigger: 'item', // 触发类型为 'item' 表示针对数据项触发
        formatter: function (params) {
          return `匹配度: ${params.name}<br/>匹配数量: ${params.value}`;
        },
      },
    });

    // 获取 ECharts 实例并监听柱子点击事件
    const chart = getInstance();
    chart.on('click', 'series.bar', function (params) {
      // 在这里添加你想要触发的逻辑
      handleBarClick(params);
    });
  }
  // function asds(){
  //   searchFormSchemaDtail.value[0].defaultValue = 1;
  // }

  async function handleBarClick(params) {
    matching.value = params.name;

    reload();
  }

  const handleButtonClick = async (model, field, label) => {
    matching.value = label.label; // 更新 matching 值
    model.matching = label.label; // 更新输入框的值
    await reload(); // 调用表格的查询接口
  };

  async function handleOK() {
    emit('success', {});
    closeModal();
  }

  // 清除定时器
  onUnmounted(() => {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
    if (matchMaxIntervalId) {
      clearInterval(matchMaxIntervalId);
      matchMaxIntervalId = null;
    }
  });

  async function taskStatusNum() {
    let Data = await taskStatusNumApi();
    taskStatusData.value = Data.data;
  }

  onMounted(() => {
    taskStatusNum(); // 获取数据统计
  });

  function handleViewDetail(record: Recordable) {
    openphaseView(true, {
      record,
    });
  }
</script>

<style scoped>
  .custom-description :deep(.ant-descriptions-item-content span) {
    display: block;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .tabelview :deep(.vben-basic-table-form-container .ant-form) {
    margin: 0 !important;
    padding-bottom: 0 !important;
  }
</style>
